package week5;

import java.util.Arrays;

public class Ex43 {
    public static void main(String[] args) {
        long ans = 0;
        char[] arr;
        long i = 1023456789L;
        while (i < 9876543210L){
            arr = String.valueOf(i).toCharArray();
            if ((arr[3]-'0' & 1) == 0 && (arr[2]-'0'+arr[3]-'0'+arr[4]-'0') % 3 == 0
            && (arr[5]-'0') % 5 == 0 && ((arr[4]-'0')*100+(arr[5]-'0')*10+(arr[6]-'0')) % 7 == 0
            && ((arr[5]-'0')*100+(arr[6]-'0')*10+(arr[7]-'0')) % 11 == 0
            && ((arr[6]-'0')*100+(arr[7]-'0')*10+(arr[8]-'0')) % 13 == 0
            && ((arr[7]-'0')*100+(arr[8]-'0')*10+(arr[9]-'0')) % 17 == 0){
                ans += i;
            }
            i = permutation(i);
        }
        System.out.println(ans);
    }
    public static long permutation(long i){
        char[] arr = String.valueOf(i).toCharArray();
        int j;
        for (j = arr.length - 2; j >= 0; --j){
            if (arr[j] < arr[j+1])
                break;
        }
        int k;
        for (k = arr.length - 1; k >= j; --k){
            if (arr[k] > arr[j])
                break;
        }
        arr[j] = (char) (arr[j] ^ arr[k]);
        arr[k] = (char) (arr[j] ^ arr[k]);
        arr[j] = (char) (arr[j] ^ arr[k]);
        char[] arr1 = Arrays.copyOfRange(arr, 0, j + 1);
        char[] arr2 = Arrays.copyOfRange(arr, j + 1, 10);
        Arrays.sort(arr2);
        return Long.parseLong(String.valueOf(arr1) + String.valueOf(arr2));
    }
}
